package com.hung.trade.order.mq.processer;

import com.alibaba.fastjson.JSON;
import com.hung.trade.common.constants.TradeEnums;
import com.hung.trade.common.protocol.OrderCancelMessage;
import com.hung.trade.common.rocketmq.IMessageProcesser;
import com.hung.trade.dao.mapper.TradeOrderMapper;
import com.hung.trade.dao.pojo.TradeOrder;
import com.hung.trade.dao.pojo.TradeOrderExample;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author hungki
 * @createTime 2018-10-09 下午 2:18
 */
public class OrderCancelProcesser implements IMessageProcesser {
    private static final Logger logger = LoggerFactory.getLogger(OrderCancelProcesser.class);
    @Autowired
    private TradeOrderMapper tradeOrderMapper;
    @Override
    public boolean heandlerMessage(MessageExt messageExt) {
        try {
            String body =new String(messageExt.getBody(),"UTF-8");
            String topic = messageExt.getTopic();
            String msgId = messageExt.getMsgId();
            String keys = messageExt.getKeys();
            String tags = messageExt.getTags();
            logger.info(String.format("recive message [ body = %s ] ",body));

            OrderCancelMessage orderCancelMessage = JSON.parseObject(body,OrderCancelMessage.class);
            TradeOrder tradeOrder = new TradeOrder();
            tradeOrder.setUserId(orderCancelMessage.getUserId());
            tradeOrder.setOrderId(orderCancelMessage.getOrderId());
            tradeOrder.setOrderStatus(TradeEnums.OrderStatusEnum.CANCEL.getStatusCode());

            TradeOrderExample tradeOrderExcemple = new TradeOrderExample();
            tradeOrderExcemple.createCriteria().andOrderIdEqualTo(orderCancelMessage.getOrderId())
                    .andUserIdEqualTo(orderCancelMessage.getUserId())
                    .andOrderStatusEqualTo(TradeEnums.OrderStatusEnum.NO_CONFIRM.getStatusCode());
            int i=tradeOrderMapper.updateByExampleSelective(tradeOrder,tradeOrderExcemple);
            if(i==0){
                logger.info("订单取消，修改不可见订单为撤销状态，没有查到不可见订单，记录到数据库，消息标记为消费成功");
                return true;
            }else{
                logger.info("订单取消，修改不可见订单为撤销状态，成功,顾消息标记为消费成功");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
